package com.itboye.mengwu.buy.ui;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.Observable;
import java.util.Observer;

import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.itboye.config.GlobalConfig;
import com.itboye.core.alert.ByAlert;
import com.itboye.core.object.BaseActivity;
import com.itboye.core.object.ResultEntity;
import com.itboye.core.object.SpPublicParams;
import com.itboye.core.utils.DensityUtil;
import com.itboye.core.utils.SPUtils;
import com.itboye.core.utils.XImageLoader;
import com.itboye.mengwu.R;
import com.itboye.mengwu.app.ui.aiwujia.RedBagActivity;
import com.itboye.mengwu.app.ui.mymeng.DaiJinQuanWeiShiYong;
import com.itboye.mengwu.app.ui.mymeng.personsettings.AddressManageActivity;
import com.itboye.mengwu.data.model.AddressQueryModel;
import com.itboye.mengwu.data.model.OrderBean;
import com.itboye.mengwu.data.model.RedBagModel;
import com.itboye.mengwu.data.model.ShopCarBean;
import com.itboye.mengwu.data.model.ShopCarBeanCopy;
import com.itboye.mengwu.data.model.ShopCarBeanCopy.StoreList;
import com.itboye.mengwu.data.model.ShopCarBeanCopy.StoreList.Cart;
import com.itboye.mengwu.data.model.StoreFavourableBean;
import com.itboye.mengwu.data.presenter.AddressQueryPresenter;
import com.itboye.mengwu.data.presenter.OrderPresenter;
import com.itboye.mengwu.data.presenter.RedBagPresenter;
import com.itboye.mengwu.main.FragmentShopcart;
import com.itboye.mengwu.ui.shop.DaPaiGouRootBean;

//import com.alipay.sdk.app.PayTask;

public class DapeigouQueRenDingDan extends BaseActivity implements Observer {
	ArrayList<Cart> arrayList = new ArrayList<>();
	private ViewGroup goodsList;
	private ViewGroup other, store;
	AddressQueryPresenter addressQueryPresenter;
	TextView shouhuoInfo;
	RelativeLayout addAddress;
	private ArrayList<AddressQueryModel> array;
	private String addressId;
	ImageView back;
	TextView txt_title, ok, heji, hongbao, daijinquan, goodsTotalPrice;
	StringBuilder stringBuilder = new StringBuilder();
	String ids;
	double price;
	String type;
	private OrderPresenter orderPresenter;
	ArrayList<String> idsArray = new ArrayList<>();
	ArrayList<ShopCarBeanCopy.StoreList> arrayHash = new ArrayList<ShopCarBeanCopy.StoreList>();
	private EditText liuyan;
	StringBuffer buffer = new StringBuffer();
	boolean isLijiBuy;
	private ShopCarBean bean;
	protected String uid;
	private StoreList storeBean;
	RelativeLayout re_redbag, youhuiquan;
	private RedBagPresenter bagPresenter;
	private ArrayList<RedBagModel> arrayListRedBag;// 红包
	private ArrayList<RedBagModel> arrayListCoupon = new ArrayList<>();// 优惠券
	private String redBagId = "";
	protected String couponIds = "";
	private String getFreightCost = "";// 运费
	private TextView yunfei, youhui;
	private double youhuiHongBao, youHuiYouHuiQuan, YunFei, storeYouHui,
			goodsTotal;
	private ArrayList<EditText> arrayListEdit = new ArrayList<>();
	protected String[] noteContent;
	private StoreFavourableBean storeFavourableBean;
	double packagePrice;//
	boolean hasEnableRedbag, hasEnableRevolop;
	private double prePrice;
	RelativeLayout youhuiContainer;
	private RedBagModel model;
	DaPaiGouRootBean daPaiGouRootBean = new DaPaiGouRootBean();
	StringBuffer idStringBuffer = new StringBuffer();
	RelativeLayout shangpinzonge;
	private ArrayList<Integer> counts = new ArrayList<>();
	StringBuffer countsBuffer = new StringBuffer();
	StringBuffer pskuBuffer = new StringBuffer();
	protected String note;
	EditText editLiuyan;

	@Override
	public int initView() {
		// TODO Auto-generated method stub
		return R.layout.activity_queren_dingdan;
	}

	@SuppressWarnings("unchecked")
	@Override
	public void onMyCreate() {
		int h = DensityUtil.dip2px(5f);
		uid = SPUtils.get(DapeigouQueRenDingDan.this, null, SpPublicParams.UID,
				"") + "";
		daPaiGouRootBean = (DaPaiGouRootBean) getIntent().getSerializableExtra(
				"model");
		counts = getIntent().getIntegerArrayListExtra("counts");
		shangpinzonge.setVisibility(View.GONE);
		youhuiContainer.setVisibility(View.GONE);
		packagePrice = Double.parseDouble(daPaiGouRootBean.getPackagePrice());
		Log.e("hu 1", price + "" + counts);

		if (daPaiGouRootBean != null) {
			// for (int i = 0; i < dapeigouBean.getItems().size(); i++) {
			// View viewStore = LayoutInflater.from(getApplicationContext())
			// .inflate(R.layout.querendingdan_header2, null);
			// TextView storeName = (TextView) viewStore
			// .findViewById(R.id.storeName);
			// storeName.setText(arrayHash.get(i).getName());
			// store.addView(viewStore);
			// orderPresenter.getStoreFavourable(storeBean.getId());
			for (int i = 0; i < daPaiGouRootBean.getItems().size(); i++) {
				// price += (Double.parseDouble(arrayHash.get(i)
				// .getCarts().get(j).getPrice()) * Integer
				// .parseInt(arrayHash.get(i).getCarts().get(j)
				// .getCount()));
				// buffer.append(arrayHash.get(i).getCarts().get(j)
				// .getId()
				// + "-");
				View v = LayoutInflater.from(getApplicationContext()).inflate(
						R.layout.querendingdan_header3, null);
				ImageView img = (ImageView) v.findViewById(R.id.img);
				TextView name = (TextView) v.findViewById(R.id.name);
				TextView guige = (TextView) v.findViewById(R.id.guige);
				TextView jiage = (TextView) v.findViewById(R.id.jiage);
				TextView shuliang = (TextView) v.findViewById(R.id.shuliang);
				shuliang.setText(counts.get(i) + "");
				idStringBuffer.append(daPaiGouRootBean.getItems().get(i)
						.getPId()
						+ ",");
				countsBuffer.append(counts.get(i) + ",");
				pskuBuffer.append(daPaiGouRootBean.getItems().get(i)
						.getSkuInfo().getId()
						+ ",");
				Log.e("hu 1.1",
						countsBuffer.toString() + "" + pskuBuffer.toString());
				name.setText(daPaiGouRootBean.getItems().get(i).getName());
				if (daPaiGouRootBean.getItems().get(i).getSkuInfo() != null)
					guige.setText(daPaiGouRootBean.getItems().get(i)
							.getSkuInfo().getSkuDesc());
				// jiage.setText("￥"
				// +dapeigouBean.getItems().get(i).getPrice());
				// shuliang.setText("x"
				// + arrayHash.get(i).getCarts().get(j).getCount());
				XImageLoader.load(GlobalConfig.API_URL + "/picture/index?id="
						+ daPaiGouRootBean.getItems().get(i).getMainImg(), img);
				android.widget.LinearLayout.LayoutParams layoutParams = new android.widget.LinearLayout.LayoutParams(
						android.widget.LinearLayout.LayoutParams.MATCH_PARENT,
						android.widget.LinearLayout.LayoutParams.WRAP_CONTENT);
				layoutParams.setMargins(5, 5, 5, 5);
				goodsList.addView(v, layoutParams);
				View divider = new View(getApplicationContext());
				divider.setLayoutParams(new LayoutParams(
						LayoutParams.MATCH_PARENT, h));
				divider.setBackgroundColor(getResources().getColor(
						R.color.white));
				goodsList.addView(divider);
				goodsTotalPrice.setText("￥" + price);
				Log.e("hu 2", price + "");
				// goodsList.addView(divider);
			}
			buffer.append(",");
		}

		orderPresenter = new OrderPresenter(this);
		txt_title.setText("确认订单");
		isLijiBuy = getIntent().getBooleanExtra("isLiJiBuy", false);
		bagPresenter = new RedBagPresenter(this);
		model = new RedBagModel();
		model.setUid(uid);
		model.setUse_status("0");

		getDefaultLocation();
		addAddress.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(DapeigouQueRenDingDan.this,
						AddressManageActivity.class);
				intent.putExtra("type", 1);
				startActivityForResult(intent, 101);
			}
		});
		back.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
		});
		// 跳转红包
		re_redbag.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (hasEnableRedbag) {
					Intent intent = new Intent(DapeigouQueRenDingDan.this,
							RedBagActivity.class);
					intent.putExtra("price", prePrice);
					startActivityForResult(intent, 103);
				}
			}
		});

		youhuiquan.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (hasEnableRevolop) {
					Intent intent = new Intent(DapeigouQueRenDingDan.this,
							DaiJinQuanWeiShiYong.class);
					intent.putExtra("price", prePrice);
					startActivityForResult(intent, 104);
				} else {

				}
			}
		});

		/**
		 * 提交订单
		 */
		ok.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				note = editLiuyan.getText().toString();
				if (isLijiBuy) {
					Log.e("hu money", price + "idStringBuffer" + idStringBuffer
							+ "countsBuffer" + countsBuffer + "pskuBuffer"
							+ pskuBuffer + daPaiGouRootBean.getId());
					orderPresenter.buyInstant(uid, idStringBuffer.substring(0,
							idStringBuffer.length() - 1), countsBuffer
							.substring(0, countsBuffer.length() - 1),
							pskuBuffer.substring(0, pskuBuffer.length() - 1),
							redBagId, couponIds, "", note, addressId,
							"android", daPaiGouRootBean.getId());
				}
			}
		});
	}

	private void caculateTotalPrice() {
		System.out.println("各种抵扣" + price + ":" + YunFei + ":" + youhuiHongBao
				+ ":" + youHuiYouHuiQuan + ":" + storeYouHui);
		prePrice = price + YunFei;
		price = price + YunFei - youhuiHongBao - youHuiYouHuiQuan
				+ packagePrice;
		if (price <= 0) {
			price = 0.01;
		}
		heji.setText("￥" + price);
		Log.e("hu end", price + "");
		heji.setTag(price);
	}

	@Override
	protected void onActivityResult(int arg0, int arg1, Intent arg2) {
		// TODO Auto-generated method stub
		super.onActivityResult(arg0, arg1, arg2);
		if (arg0 == 101 && arg1 == 102) {
			if (arg2 != null) {
				addressId = arg2.getStringExtra("id");
				shouhuoInfo.setText(arg2.getStringExtra("wholelocation")
						+ arg2.getStringExtra("detail") + "\n"
						+ arg2.getStringExtra("name") + "     "
						+ arg2.getStringExtra("phone"));
			}
		} else if (arg0 == 103 && arg1 == 105) {// 红包回调
			String redMoney = arg2.getStringExtra("redMoney");
			youhuiHongBao = Double.parseDouble(redMoney);
			redBagId = arg2.getStringExtra("redId");
			hongbao.setText("红包-￥" + redMoney);
			caculateTotalPrice();
		} else if (arg0 == 104 && arg1 == 106) {// 优惠券回调
			String youHuiMoney = arg2.getStringExtra("youHuiMoney");
			youHuiYouHuiQuan = Double.parseDouble(youHuiMoney);
			redBagId = arg2.getStringExtra("youHuiId");
			daijinquan.setText("优惠券-￥" + youHuiMoney);
			caculateTotalPrice();
		}
	}

	private void getDefaultLocation() {
		// TODO Auto-generated method stub
		addressQueryPresenter = new AddressQueryPresenter(this);
		addressQueryPresenter.queryAddress(uid);
	}

	@SuppressWarnings("unchecked")
	@Override
	public void update(Observable observable, Object data) {
		// TODO Auto-generated method stub
		ResultEntity entity = handlerError(data);
		if (entity != null) {
			if (entity.getEventType() == AddressQueryPresenter.AddressQuerySuccessEvent) {
				array = (ArrayList<AddressQueryModel>) entity.getData();
				for (int i = 0; i < array.size(); i++) {
					if (array.get(i).getDefault() == 1) {
						shouhuoInfo.setText(array.get(i).getProvince()
								+ array.get(i).getCity()
								+ array.get(i).getArea()
								+ array.get(i).getDetailinfo() + "\n"
								+ array.get(i).getContactname() + "     "
								+ array.get(i).getMobile());
						addressId = array.get(i).getId();
					} else {
						shouhuoInfo.setText(array.get(0).getProvince()
								+ array.get(0).getCity()
								+ array.get(0).getArea()
								+ array.get(0).getDetailinfo() + "\n"
								+ array.get(0).getContactname() + "     "
								+ array.get(0).getMobile());
						addressId = array.get(0).getId();
					}
				}
				if (!isLijiBuy) {
					bagPresenter.caculateFreightCost(
							uid,
							addressId,
							buffer.toString().substring(0,
									buffer.toString().length() - 2));
				} else {// 立即购买
					System.out.println("uid:"
							+ uid
							+ "addressId"
							+ addressId
							+ "idStringBuffer"
							+ idStringBuffer.substring(0,
									idStringBuffer.length() - 1) + "count"
							+ "1");
					bagPresenter.caculateFreightCost(uid, addressId,
							idStringBuffer.substring(0,
									idStringBuffer.length() - 1), countsBuffer
									.substring(0, countsBuffer.length() - 1));
				}
				bagPresenter.query(model);// 获取优惠券
			} else if (entity.getEventType() == OrderPresenter.OrderShengchengSuccess) {
				ByAlert.alert("成功");
				Intent intentBroad = new Intent(FragmentShopcart.changeCart);// 通知购物车界面更新UI
				sendBroadcast(intentBroad);
				OrderBean bean = (OrderBean) entity.getData();
				Intent intent = new Intent(DapeigouQueRenDingDan.this,
						PayTypeActivity.class);
				intent.putExtra("model", bean);
				startActivity(intent);
				finish();
			} else if (entity.getEventType() == OrderPresenter.OrderShengchengFail) {
				ByAlert.alert("失败");
			} else if (entity.getEventType() == OrderPresenter.PayInstant_success) {

				Intent intentBroad = new Intent(FragmentShopcart.changeCart);// 通知购物车界面更新UI
				sendBroadcast(intentBroad);

//				ByAlert.alert(entity.getData() + "");
				OrderBean bean = (OrderBean) entity.getData();
				Intent intent = new Intent(DapeigouQueRenDingDan.this,
						PayTypeActivity.class);
				intent.putExtra("model", bean);
				startActivity(intent);
				finish();
			} else if (entity.getEventType() == OrderPresenter.PayInstant_Fail) {
				// ByAlert.alert("失败" + entity.getData() + "");
			} else if (entity.getEventType() == RedBagPresenter.QueryRedBagSuccess) {
				arrayListRedBag = (ArrayList<RedBagModel>) entity.getData();
				RedBagModel aa = new RedBagModel();
				// 红包通过money排序
				for (int i = 0; i < arrayListRedBag.size(); i++) {

					for (int j = i + 1; j < arrayListRedBag.size(); j++) {
						if (Double.parseDouble(arrayListRedBag.get(i)
								.getMoney().trim()) < Double
								.parseDouble(arrayListRedBag.get(j).getMoney()
										.trim())) {
							aa = arrayListRedBag.get(i);
							arrayListRedBag.set(i, arrayListRedBag.get(j));
							arrayListRedBag.set(j, aa);

						}
					}
				}

				for (int i = 0; i < arrayListRedBag.size(); i++) {// 删除不满足优惠条件的红包
					if (Double.parseDouble(arrayListRedBag.get(i)
							.getUse_condition()) > price) {
						arrayListRedBag.remove(i);
					}
				}
				Iterator<RedBagModel> iterable = arrayListRedBag.iterator();
				while (iterable.hasNext()) {// 删除优惠金额大于应付金额的红包
					RedBagModel type = iterable.next();
					if (Double.parseDouble(type.getMoney()) > price) {
						iterable.remove();
					}
				}

				// setValue(arrayListRedBag, 1);
				// for (RedBagModel string : arrayListRedBag) {
				// System.out.println("moby" + string.getMoney());
				// }
				if (arrayListRedBag.size() > 0) {
					hongbao.setText("红包-￥" + arrayListRedBag.get(0).getMoney());
					youhuiHongBao = Double.parseDouble(arrayListRedBag.get(0)
							.getMoney());

					hasEnableRedbag = true;
					redBagId = arrayListRedBag.get(0).getId();
				} else {
					hasEnableRedbag = false;
					hongbao.setText("没有达到条件的红包");
				}
				// hongbao.setText(arrayListRedBag.get(0).getName());
			} else if (entity.getEventType() == RedBagPresenter.QueryRedBagFail) {

			} else if (entity.getEventType() == RedBagPresenter.QueryCouponSuccess) {
				arrayListCoupon = (ArrayList<RedBagModel>) entity.getData();
				RedBagModel aa = new RedBagModel();
				// 优惠券通过money排序
				for (int i = 0; i < arrayListCoupon.size(); i++) {

					for (int j = i + 1; j < arrayListCoupon.size(); j++) {
						Log.e("1111", i + "");
						Log.e("2222", j + "");
						if (Double.parseDouble(arrayListCoupon.get(i)
								.getMoney().trim()) < Double
								.parseDouble(arrayListCoupon.get(j).getMoney()
										.trim())) {
							aa = arrayListCoupon.get(i);
							arrayListCoupon.set(i, arrayListCoupon.get(j));
							arrayListCoupon.set(j, aa);

						}
					}
				}

				for (int i = 0; i < arrayListCoupon.size(); i++) {// 删除不满足优惠条件的优惠券
					System.out.println("优惠券"
							+ arrayListCoupon.get(i).getUse_condition() + "L:"
							+ price);
					if (Double.parseDouble(arrayListCoupon.get(i)
							.getUse_condition()) > price) {
						arrayListCoupon.remove(i);
					}
				}
				System.out.println("前size" + arrayListCoupon.size());
				// for (int i = 0; i < arrayListRedBag.size(); i++) {
				// System.out.println("金额："+arrayListRedBag.get(i).getMoney()+":"+price);
				// if(Double.parseDouble(arrayListRedBag.get(i).getMoney())>price){
				// //
				// System.out.println("要移除的"+arrayListRedBag.get(i).getMoney()+":"+price);
				// arrayListRedBag.remove(i);
				// }
				// }
				Iterator<RedBagModel> iterable = arrayListCoupon.iterator();
				while (iterable.hasNext()) {// 删除优惠金额大于应付金额的优惠券
					RedBagModel type = iterable.next();
					if (Double.parseDouble(type.getMoney()) > price) {
						iterable.remove();
					}
				}

				for (RedBagModel iterable_element : arrayListCoupon) {
					System.out.println("红包" + iterable_element.getId() + ":"
							+ iterable_element.getMoney());
				}
				if (arrayListCoupon.size() > 0) {
					hasEnableRevolop = true;

					daijinquan.setText("优惠券-￥"
							+ arrayListCoupon.get(0).getMoney());
					youHuiYouHuiQuan = Double.parseDouble(arrayListCoupon
							.get(0).getMoney());
					couponIds = arrayListCoupon.get(0).getId();
				} else {
					hasEnableRevolop = false;
					daijinquan.setText("没有达到条件的优惠券");
				}
				bagPresenter.getInfo(model);// 获取红包
			} else if (entity.getEventType() == RedBagPresenter.QueryCouponFail) {

			} else if (entity.getEventType() == RedBagPresenter.QueryFreightCostSuccess) {
				// ByAlert.alert(entity.getData() + "");
				yunfei.setText(entity.getData().equals("0") ? "包邮" : "￥"
						+ entity.getData());
				YunFei = Double.parseDouble(entity.getData() + "");
				caculateTotalPrice();
			} else if (entity.getEventType() == RedBagPresenter.QueryFreightCostFail) {
				ByAlert.alert(entity.getData() + ">>>>+++");
			} else if (entity.getEventType() == RedBagPresenter.QueryFreightCostGoodsSuccess) {
				// ByAlert.alert(entity.getData() + "");
				yunfei.setText(entity.getData().equals("0") ? "包邮" : "￥"
						+ entity.getData());
				YunFei = Double.parseDouble(entity.getData() + "");
				caculateTotalPrice();
			} else if (entity.getEventType() == RedBagPresenter.QueryFreightCostGoodsFail) {
				ByAlert.alert(entity.getData() + "2");
			} else if (entity.getEventType() == OrderPresenter.getFavourableSuccess) {
				storeFavourableBean = (StoreFavourableBean) entity.getData();
				if (price > Double.parseDouble(storeFavourableBean
						.getCondition())) {
					storeYouHui = Double.parseDouble(storeFavourableBean
							.getDicountMoney());
					youhui.setText("-￥" + storeFavourableBean.getDicountMoney());
					price = price - storeYouHui;
				} else {
					youhui.setText("不满足优惠条件");
				}
				caculateTotalPrice();
			}

		}
	}

	/**
	 * 冒泡排序
	 * 
	 * @param list
	 *            需要排序的集合
	 * @param type
	 *            排序类型 0：正序 1：倒序
	 * */
	public void setValue(ArrayList<RedBagModel> list, int type) {
		System.out.println("价格" + price);
		for (int i = 0; i < list.size(); i++) {
			if (Double.parseDouble(list.get(i).getUse_condition()) > price) {
				list.remove(i);
			}
		}
		for (int i = 0; i < list.size(); i++) {// 循环List集合，开始于下标0

			for (int j = i + 1; j < list.size(); j++) {// 循环List集合，开始于下标0+1
				double a = Double.parseDouble(list.get(i).getMoney());// 取List集合的第n个值
				double b = Double.parseDouble(list.get(j).getMoney());// 取List集合的第n+1个值
				if (type == 0 ? a > b : a < b) {// 如果a比b大，则替换两个值的位置。
					list.set(i, list.get(j));
					list.set(j, list.get(i));
				}
			}
		}

	}
}
